/*
 *    Copyright (c) 2018-2025, nart All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: nart
 */

package com.nai365.nart.member.controller;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.excel.annotation.ResponseExcel;
import com.nai365.nart.common.log.annotation.SysLog;
import com.nai365.nart.common.security.annotation.Inner;
import com.nai365.nart.member.dto.*;
import com.nai365.nart.member.entity.Member;
import com.nai365.nart.member.entity.UserBank;
import com.nai365.nart.member.entity.Wallet;
import com.nai365.nart.member.entity.WalletChange;
import com.nai365.nart.member.service.MemberService;
import com.nai365.nart.member.service.UserBankService;
import com.nai365.nart.member.service.WalletChangeService;
import com.nai365.nart.member.service.WalletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 会员
 *
 * @author baogs
 * @date 2022-07-01 10:52:57
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/member")
@Api(value = "member", tags = "会员管理")
public class MemberController {

	private final MemberService memberService;
	private final UserBankService userBankService;

	private final WalletService  walletService;

	private final WalletChangeService walletChangeService;



	/**
	 * 分页查询
	 *
	 * @param page   分页对象
	 * @param member 会员
	 * @return
	 */
	@ApiOperation(value = "分页查询", notes = "分页查询")
	@GetMapping("/page")
	public R getMemberPage(Page page, Member member) {
		return R.ok(memberService.page(page, Wrappers.query(member)));
	}

	@ApiOperation(value = "查询已实名用户", notes = "分页查询")
	@GetMapping("/find/verify/member")
	public R<Page<Member>> findVerifyMember(Page<Member> page, String phone) {
		LambdaQueryWrapper<Member> queryWrapper = Wrappers.lambdaQuery();
		if (!StringUtils.isEmpty(phone)) {
			queryWrapper.like(Member::getMobile, phone);
		}
		return R.ok(memberService.page(page, queryWrapper));
	}


	/**
	 * 通过id查询会员
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}")
	public R getById(@PathVariable("id") Long id) {
		Member byId = memberService.getById(id);
		JSONObject member = JSONUtil.parseObj(byId);
		String password = byId.getPayPass();
		UserBank userBankByUserId = userBankService.findUserBankByUserId(byId.getUserId());
		if (StrUtil.isNotBlank(password)){
			member.putOpt("payPass",true);
		}else {
			member.putOpt("payPass",false);
		}
		if(userBankByUserId != null){
			member.putOpt("userBank",true);
		} else {
			member.putOpt("userBank",false);
		}

		return R.ok(member);
	}

	/**
	 * 新增会员
	 *
	 * @param member 会员
	 * @return R
	 */
	@ApiOperation(value = "新增会员", notes = "新增会员")
	@SysLog("新增会员")
	@PostMapping
	public R save(@RequestBody Member member) {
		return R.ok(memberService.save(member));
	}

	/**
	 * 修改会员
	 *
	 * @param member 会员
	 * @return R
	 */
	@ApiOperation(value = "修改会员", notes = "修改会员")
	@SysLog("修改会员")
	@PutMapping
	public R updateById(@RequestBody Member member) {
		return R.ok(memberService.updateById(member),"修改成功");
	}

	/**
	 * 通过id删除会员
	 *
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id删除会员", notes = "通过id删除会员")
	@SysLog("通过id删除会员")
	@DeleteMapping("/{id}")
	public R removeById(@PathVariable Long id) {
		return R.ok(memberService.removeById(id));
	}


	/**
	 * 导出excel 表格
	 *
	 * @param member 查询条件
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	public List<Member> export(Member member) {
		return memberService.list(Wrappers.query(member));
	}

	/**
	 * 根据手机号查询会员
	 *
	 * @param phone
	 * @return
	 */
	@GetMapping("/findMemberByPhone/{phone}")
	@Inner
	public Member findMemberByPhone(@PathVariable("phone") String phone) {
		Member member = memberService.findMemberByPhone(phone);
		return member;
	}


	@PostMapping("/save_inner")
	@Inner
	public R save_inner(@RequestParam("userId") Long userId, @RequestParam("number") String number, @RequestParam("inviteId") Long inviteId) {
		Member member1 = memberService.getById((long) userId);
		if (member1 != null) {
			Long parentId = member1.getParentId();
			parentId = parentId == null ? 0 : parentId;
			if (parentId.intValue() == 0 && !userId.equals(inviteId)) {
				member1.setParentId(inviteId);
				updateById(member1);
				return R.ok();
			}
			return R.ok();
		} else {
			//对昵称进行处理
			String nickName = "";
			if (ReUtil.isMatch("[1-9]\\d*", number) || StrUtil.isEmpty(number)) {
				String s = cn.hutool.core.lang.UUID.fastUUID().toString();
				String substring = s.substring(s.lastIndexOf("-") + 1);
				nickName = "nart" + substring;
			} else {
				nickName = number;
			}
			if (nickName.length() >= 20) {
				nickName = "nart" + nickName.substring(0, 10);
			}
			Member member = new Member();
			member.setId(userId);
			member.setUserId(userId);
			member.setMobile(number);
			member.setUsername(number);
			member.setNickname(nickName);
			member.setParentId(inviteId);

			Wallet wallet = new Wallet();
			wallet.setId(userId);
			wallet.setUserId(userId);
			wallet.setPhone(number);
			walletService.save(wallet);
			return R.ok(save(member));
		}
	}



	/**
	 * 根据会员id列表查询会员信息
	 *
	 * @param idList 会员id
	 * @return 会员列表
	 * @see com.nai365.nart.member.dto.SimpleMemberDto
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/list/ids")
	public R<List<SimpleMemberDto>> getByIds(@RequestParam("idList") Collection<Serializable> idList) {
		return R.ok(memberService.findByIds(idList));
	}

	/**
	 * 根据用户userId 更新用户链状态和链地址
	 *
	 * @return
	 */
	@PostMapping("/updateMemberIsVerify")
	@Inner
	public R updateMemberIsVerify(@RequestBody ChainVerifyUserDto chainVerifyUserDto) {

		return R.ok(memberService.updateMemberIsVerify(chainVerifyUserDto));
	}
	/**
	 * 设置支付密码
	 */
	@ApiOperation(value = "设置支付密码", notes = "设置支付密码")
	@PostMapping("/setPayPass")
	public R<Boolean> setPayPass(@RequestBody PayPassDto payPassDto){
		Boolean isSuccess=memberService.setPayPass(payPassDto);
		return R.ok(isSuccess,"设置密码成功！");
	}
	/**
	 * 余额支付
	 */
	@ApiOperation(value = "余额支付", notes = "余额支付")
	@PostMapping("/payByRemainder")
	public R<Boolean> payByRemainder(@RequestBody RemainderDto remainderDto){
		R<Boolean> isSuccess=memberService.payByRemainder(remainderDto);
		return isSuccess;
	}
	@GetMapping("/findCoinAdress/{merberId}")
	@Inner
	public Member findCoinAdress(@PathVariable("merberId") Long merberId){
		Member m=memberService.findCoinAdress(merberId);
		return m;
	}
	@PostMapping("/findHeaderAndNickname")
	@Inner
	public R findHeaderAndNickname(@RequestBody List<Long> ids){

		List<Member> list = memberService.list(Wrappers.<Member>lambdaQuery()
				.select(Member::getHeader, Member::getNickname,Member::getUserId).in(Member::getUserId, ids));
		Map<Long, Member> collect = list.parallelStream().collect(Collectors.toMap(Member::getUserId, Function.identity()));
		return R.ok(JSONUtil.parse(collect));
	}

	@GetMapping("/findUserPayPassByUserId/{userId}")
	@Inner
	public Member findUserPayPassByUserId(@PathVariable("userId") Long userId){
		return memberService.getById(userId);
	};

	/**
	 * 藏品回收
	 * @param recoveryDto
	 * @return
	 */
	@PostMapping("/recoveryGoods")
	@Inner
	public R<WalletChange> recoveryGoods(@RequestBody RecoveryDto recoveryDto){
		System.out.println("接收到的参数是-----------------------"+recoveryDto);
		//更据用户id 更新用户的余额
		LambdaQueryWrapper<Wallet> walletLambdaQueryWrapper = new LambdaQueryWrapper<>();
		walletLambdaQueryWrapper.eq(Wallet::getUserId,recoveryDto.getUserId());
		Wallet wallet = walletService.getOne(walletLambdaQueryWrapper);

		wallet.setRmbBalance(wallet.getRmbBalance().add(recoveryDto.getRecoveryRMB()));

		System.out.println("wallet is---------"+wallet.toString());
		boolean issuccess = walletService.saveOrUpdate(wallet);
		//新增用户流水日志
		WalletChange walletChange = new WalletChange();
		walletChange.setUserId(recoveryDto.getUserId());
		walletChange.setCurrentBalance(wallet.getRmbBalance().add(recoveryDto.getRecoveryRMB()));
		walletChange.setRmbValue(recoveryDto.getRecoveryRMB());
		walletChange.setNartValue(BigDecimal.ZERO);
		walletChange.setOrderSn(java.util.UUID.randomUUID().toString().replace("-",""));
		walletChange.setSkuName("回收藏品");
		walletChange.setType(6);
		walletChange.setFromUserId(recoveryDto.getFromUserId());
		walletChange.setToUserId(recoveryDto.getToUserId());
		walletChangeService.save(walletChange);
		return R.ok(walletChange,"回收成功！");
//		return memberService.recoveryGoods(recoveryDto);
	}
}
